package com.saicent.note.controller;

import java.io.FileOutputStream;
import java.io.InputStream;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;

import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.saicent.note.core.ArticleManager;
import com.saicent.support.web.ws.rs.Response;

@Controller
@RequestMapping("system")
public class SystemController extends AbstractController {
	
	private Log log = LogFactory.getLog(getClass());
	@RequestMapping("reload")
	@ResponseBody
	public Response reloadArticle() {
		log.info("Start reload articles.");
		try {
			((ArticleManager) contextAttribute(ArticleManager.class.getName())).reload();
		} catch (Exception e) {
			return Response.build(Response.RESPONSE_STATUS_ERROR).error(500, e.getMessage());
		}
		return Response.build(Response.RESPONSE_STATUS_OK);
	}
	
	@RequestMapping("upload")
	public String uploadArticle(@RequestParam("article")MultipartFile file) throws Exception {
		log.info(file.getName());
		Path targetPath = Paths.get(getRealPath(JSP_BASE_LOCATION), "notes", UUID.randomUUID().toString() + ".jsp");
		try (FileOutputStream outputStream = new FileOutputStream(targetPath.toFile());
				InputStream inputStream = file.getInputStream()) {
			IOUtils.copy(inputStream, outputStream);
			outputStream.flush();
			IOUtils.closeQuietly(outputStream);
			((ArticleManager) contextAttribute(ArticleManager.class.getName())).reload();
		}
		return "redirect:/menu";
	}
}
